import { acceptHMRUpdate, defineStore } from "pinia";
import { shallowReactive, shallowRef } from "vue";
import { TaskItem } from "./task-item.ts";
import { useDevEnvPanelStore } from "@/modules/dev-env/store/panel-store.ts";

/**
 * 任务管理
 */
export const useTaskStore = defineStore("dev-env.task", () => {
  const panelStore = useDevEnvPanelStore();

  /**
   * 正在进行的任务列表
   */
  const taskList = shallowRef<TaskItem[]>([]);

  /**
   * 添加任务
   * @param task
   */
  const addTask = (task: TaskItem) => {
    const t0 = taskList.value.find(it => it.id === task.id);
    if (t0) {
      return t0;
    }

    const list = [...taskList.value];
    const t = shallowReactive(task);
    t.on("complete", () => deleteTask(t.id));
    t.on("cancel", () => deleteTask(t.id));
    list.push(t);
    taskList.value = list;
    return t;
  };

  /**
   * 删除任务
   * @param id 任务ID
   */
  const deleteTask = (id: string) => {
    const idx = taskList.value.findIndex(t => t.id == id);
    if (idx !== -1) {
      const list = [...taskList.value];
      list.splice(idx, 1);
      taskList.value = list;

      if (list.length === 0) {
        // 关闭任务面板
        panelStore.taskPanelOpen = false;
      }
    }
  };

  return {
    taskList: taskList,
    addTask: addTask,
    deleteTask: deleteTask,
  };
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useTaskStore, import.meta.hot));
}
